package com.atguigu.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.msmservice.service.MsmService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @ClassName MsmServiceImpl
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/6/23
 * @Version 1.0
 */
@Service
public class MsmServiceImpl implements MsmService {
    /**
     * 发送短信验证码
     * @param codeMap
     * @param phone
     * @return
     */
    @Override
    public boolean send(Map<String, Object> codeMap, String phone) {

        if(StringUtils.isEmpty(phone)) return false;

        //固定参数设置
        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI4G8R4MUz3fA4EaB7ztrX", "mSvRQbYnEWPN5V90EOFWejmS35c551");
        //短信发送客户端
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //这些参数的值都是固定的，不能改变
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        //这些参数名都是固定的，不能修改
        //电话号码
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称，从自己申请的签名名称获取
        request.putQueryParameter("SignName", "我的乐学在线教育网站");
        //模板code，从自己申请的短信模板获取
        request.putQueryParameter("TemplateCode",   "SMS_193522865");
        //需要传递Json数据
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(codeMap));
        try {
            //执行发送
            CommonResponse response = client.getCommonResponse(request);
            //返回发送状态
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
